import {baseUrl} from "../../config";
import {request} from "../../utils/util";
let app = getApp()

Page({
  data: {
    userInfo: {},
  },
  toEditNickname () {
    wx.navigateTo({
      url: '/pages/editNickname/index'
    })
  },
  toEditPhone () {
    wx.navigateTo({
      url: '/pages/editPhone/index'
    })
  },
  choosePortrait () {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        // tempFilePath可以作为img标签的src属性显示图片
        let files = res.tempFilePaths
        wx.showLoading({
          title: '加载中..',
          mask: true
        })
        wx.uploadFile({
          url: `${baseUrl}/api/file`,
          filePath: files[0],
          name: 'img',
          formData: {
            type: 'avatar'
          },
          success: (result) => {
            wx.hideLoading()
            if (result.statusCode === 200) {
              let data = JSON.parse(result.data)
              if (data.code === 200) {
                this.save(data.data.url)
              } else {
                wx.showToast({
                  title: data.message,
                  icon: 'none',
                  duration: 2000
                })
              }
            } else {
              wx.showToast({
                title: result.errMsg,
                icon: 'none',
                duration: 2000
              })
            }
          },
          fail(err) {
            console.log(err)
          }
        })
      }
    })
  },
  save(avatarUrl) {
    wx.showLoading({
      title: '加载中..',
      mask: true
    })
    request({
      url: '/api/web/personal/avatar',
      method: 'PUT',
      data: {
        value: avatarUrl
      },
      success: ({ code, message }) => {
        wx.hideLoading()
        if (code === 200) {
          wx.showToast({
            title: '修改成功！',
            icon: 'success',
            duration: 2000
          })
          this.setData({
            userInfo: {
              ...this.data.userInfo,
              avatarUrl
            }
          })
          app.globalData.userInfo = this.data.userInfo
          wx.setStorage({
            key: "userInfo",
            data: this.data.userInfo
          })
        } else {
          wx.showToast({
            title: message,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  onShow () {
    wx.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#000000',
      animation: {
        duration: 400,
        timingFunc: 'easeIn'
      }
    })
    this.setData({
      userInfo: app.globalData.userInfo
    })
  },
})
